<!--
 * @Author: your name
 * @Date: 2021-10-14 15:32:03
 * @LastEditTime: 2021-11-12 17:19:53
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \autotestplant_frontend\src\components\users\Users.vue
-->
<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>后台管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 用户搜索框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible= true"> 添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe >
        <!-- <el-table-column  fixed type="index" label="#" width="180" >
        </el-table-column> -->
        <el-table-column fixed prop="email" label="邮箱名" width="180" ></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话号码" width="180"></el-table-column>
        
        <el-table-column prop="mg_state" label="是否可以使用" width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" :active-value="true" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-tooltip  effect="dark" content="修改基本信息" placement="top" >
              <el-button type="primary" icon="el-icon-edit" circle  size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip  effect="dark" content="删除用户" placement="top" >
              <el-button type="danger" icon="el-icon-delete" circle  size="mini" @click="removeUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip  effect="dark" content="分配角色" placement="top" >
              <el-button type="warning" icon="el-icon-setting" circle  size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="create_time" label="创建时间"> </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagennum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesizi"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    <!-- 添加用户的对话框 -->
      <el-dialog title="添加新用户" :visible.sync="addDialogVisible" width="50%" class="dialog_form" @close="addDialogClose">
        <!-- 内容主体区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="addForm.username" placeholder="请输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" placeholder="请输入邮箱名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%"  @close="editDialogClose">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px" >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="editForm.username" placeholder="请输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="请输入邮箱名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" placeholder="请输入密码" type="password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>


    </el-card>
  </div>
</template>

<script>
export default {
  data() {

    // 验证邮箱的规则
     var checkEmail = (rule, value, callback) => {
        const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if(regEmail.test(value)){
          return callback()
        }
        callback(new Error('请输入合法的邮箱'));
      }

    // 验证手机号的规则
     var checkphone = (rule, value, callback) => {
        const regPhone = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]14[57])[0-9]{8}$/
        console.log(value);
        if(regPhone.test(value)){
          return callback()
        }
        callback(new Error('请输入合法的手机号'));
      }
    

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '', // 查询参数
        pagennum: 1, // 当前页码
        pagesizi: 10, // 每页显示条数
      },
      userlist: [],
      total: 0, // 总条数
      addDialogVisible:false, // 控制添加用户对话框的显示与隐藏
      
      // 添加用户表单数据
      addForm:{
        username:"",
        email:"",
        password:"",
        phone:"",
      },
      // 添加表单校验规则
      addFormRules:{
        username:[{required:true,message:"请输入用户姓名",trigger:"blur"},{min:2,max:10,message:"用户名在2~10个字符之间",trigger:"blur"}],
        email:[{required:true,message:"请输入邮箱",trigger:"blur"},{validator:checkEmail,trigger:"blur"}],
        password:[{required:true,message:"请输入密码",trigger:"blur"},{min:6,max:15,message:"密码6~15个字符之间",trigger:"blur"}],
        phone:[{required:true,message:"请输入手机号",trigger:"blur"},{validator:checkphone,trigger:"blur"}],
        mobile:[{required:true,message:"请输入手机号",trigger:"blur"},{validator:checkphone,trigger:"blur"}],
        },

      editDialogVisible:false, // 控制修改用户对话框的显示与隐藏
      // 查询到的用户信息对象
      editForm:{
        },
      // 修改表单校验规则
      editFormRules:{
      username:[{required:true,message:"请输入用户姓名",trigger:"blur"},{min:2,max:10,message:"用户名在2~10个字符之间",trigger:"blur"}],
      email:[{required:true,message:"请输入邮箱",trigger:"blur"},{validator:checkEmail,trigger:"blur"}],
      password:[{required:true,message:"请输入密码",trigger:"blur"},{min:6,max:15,message:"密码6~15个字符之间",trigger:"blur"}],
      phone:[{required:true,message:"请输入手机号",trigger:"blur"},{validator:checkphone,trigger:"blur"}],
      },


    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('auth_app/user_list/', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data
      this.total = res.total
      console.log(this.userlist)
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize){
      console.log(newSize)
      this.queryInfo.pagesizi = newSize
      this.getUserList()
  },
  // 监听 页码值 改变的事件
    handleCurrentChange(newPage){
      console.log(newPage)
      this.queryInfo.pagennum = newPage
      this.getUserList()
  },
  // 监听 switch 开关状态的改变
   async userStateChanged(userinfo){
    console.log(userinfo)
    const {data:res} =  await this.$http.put(
      'auth_app/user/',
      { id: userinfo.id, mg_state: userinfo.mg_state }
    )
    if(res.meta.status !==200) {
      userinfo.mg_state = !userinfo.mg_state
      return this.$message.error("更新用户状态失败")
    }
    this.$message.success("更新用户状态成功")
  },
  // 监听用户对话框关闭事件
  addDialogClose() {
    this.$refs.addFormRef.resetFields()
  },
  // 点击确认按钮，添加新用户
  addUser() {
    this.$refs.addFormRef.validate(async valid => {
      console.log(valid)
      if (!valid) return
      const {data:res} =  await this.$http.post('auth_app/user/',this.addForm)

      if(res.meta.status == 201)
      {this.$message.error(res.meta.msg)}
      else{
        this.$message.success('添加用户成功')
        // 隐藏用户对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      }
    })
  },
  // 展示编辑用户对话框
  async showEditDialog(id) {
    const {data:res} =  await this.$http.get("auth_app/user/",{params:{id:id}})
    if (res.meta.status !== 200){
      return this.$message.error("获取数据失败")
    }
    this.editForm = res.data
    this.editDialogVisible = true
    console.log(res.meta.data)
  },
  // 监听修改用户框关闭事件
  editDialogClose(){
    this.$refs.editFormRef.resetFields()
  },
  // 修改用户请求
  editUserInfo(){
    // 修改表单预验证
    this.$refs.editFormRef.validate(async valid => {
      console.log(valid)
      if (!valid) return
      const {data:res} = await this.$http.put('auth_app/user/',this.editForm)
      if (res.meta.status !==200){
        this.$message.error(res.meta.msg)
      }
      else{
        // 提示用户修改信息
        this.$message.success("修改用户信息成功")
        // 隐藏用户对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this.getUserList()

      }
    })

  },


  // 删除用户
  removeUserById(id) {
    this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data : res} =  await this.$http.delete('auth_app/user/',{params:{id:id}})
          if (res.meta.status !== 200){
            this.$message.success(res.meta.msg)
          }
          this.$message({type: 'success',message: '删除成功!'});
          // 刷新用户列表
          this.getUserList()
        }).catch(() => {
          this.$message({type: 'info',message: '已取消删除'});          
        });

        
    console.log(id)

  },
 

  },
  
}
</script>

<style lang="less" scoped>
.dialog_form {
  text-align: left;
}
</style>